package com.ws.accounting.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.ws.accounting.entity.SubjectInfo;
import com.ws.accounting.repository.SubjectInfoRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class SubjectImportUtils extends AnalysisEventListener<SubjectInfo> {
    private static final Logger LOGGER = LoggerFactory.getLogger(SubjectImportUtils.class);
    private static final int BATCH_COUNT = 5;
    List<SubjectInfo> subjectInfoList = new ArrayList<SubjectInfo>();

    private SubjectInfoRepository repository;

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param repository
     */
    public SubjectImportUtils(SubjectInfoRepository repository) {
        this.repository = repository;
    }



    @Override
    public void invoke(SubjectInfo subjectInfo, AnalysisContext analysisContext) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(subjectInfo));
        subjectInfoList.add(subjectInfo);
        if (subjectInfoList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            subjectInfoList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        LOGGER.info("所有数据解析完成！");
    }




    /**
     * 加上存储数据库
     */
    private void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", subjectInfoList.size());
        repository.saveAll(subjectInfoList);
        LOGGER.info("存储数据库成功！");
    }
}
